package com.xiaoyu.izf.controller.api;

import ch.qos.logback.core.status.Status;
import com.xiaoyu.izf.model.GoodsInfo;
import com.xiaoyu.izf.model.GoodsOrder;
import com.xiaoyu.izf.model.UserAddress;
import com.xiaoyu.izf.model.UserInfo;
import com.xiaoyu.izf.model.exception.BusinessStatusEnum;
import com.xiaoyu.izf.model.page.FormResult;
import com.xiaoyu.izf.service.GoodsOrderService;
import com.xiaoyu.izf.service.GoodsService;
import com.xiaoyu.izf.service.UserAddressService;
import com.xiaoyu.izf.util.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/api/goods_order")
public class GoodsOrderApiController extends BaseApiController {

    @Autowired
    private GoodsOrderService goodsOrderService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserAddressService userAddressService;

    @RequestMapping("/order")
    @ResponseBody
    public FormResult<String> orderGet(HttpServletRequest req, int goodsId, int buyNum){
        FormResult<String> fr = new FormResult<>();
        UserInfo user = getUserByToken(req);
        GoodsInfo goods = goodsService.goodsOne(goodsId);
        if(goods==null){
            fr.setStatus(404);
            fr.setMessage("商品不存在。");
            return fr;
        }
        List<UserAddress> list = userAddressService.addressesByUid(user.getId());
        if(list==null||list.size()==0){
            return new FormResult<>(BusinessStatusEnum.ERROR,"","没有收货地址");
        }
        String orderId = "s"+System.currentTimeMillis() + (long) (Math.random() * 10000000L);
        GoodsOrder order = goodsOrderService.orderAdd(orderId,user,goods,buyNum);
        fr.setStatus(200);
        fr.setMessage("ok");
        fr.setData(orderId);

        return fr;
    }

    @RequestMapping("/list")
    @ResponseBody
    public FormResult<Page<GoodsOrder>> list(HttpServletRequest req){
        int p = ParamUtil.getInt(req,"p");
        int psize = ParamUtil.getInt(req,"psize");
        if(p==0){p=1;}
        if(psize==0)psize=10;
        FormResult<Page<GoodsOrder>> fr = new FormResult<>();
        UserInfo user = getUserByToken(req);
        Page<GoodsOrder> pagelist = goodsOrderService.listForApi(p,psize,user.getId());
        List<GoodsOrder> list = pagelist.getContent();
        if(list!=null&&list.size()>0){
            fr.setStatus(200);
            fr.setMessage("ok");
            fr.setData(pagelist);
        }else{
            fr.setStatus(404);
            fr.setMessage("没有数据。");
        }
        return fr;
    }


}
